<?php

namespace Cron\Controller;

//use Common\Controller\ApiController;
//use Think\Log;
use Think\Controller\RestController;

class LiaobaController extends RestController {

    public function _initialize() {
        $token = I('get.token');
        if (empty($token) || $token != C('JWT_KEY')) {
            $this->errorResponse('404', '请求失败，请检查');
        }
    }

    /*
     * 红包过期收回
     * 私聊红包直接余额增加，群聊红包，查出抢了多少，再减去，回收剩下的
     * 执行时间：凌晨5点，
     */

    public function recoverLuckMoney() {
        $LuckmoneyM = D('Luckmoney');
        $time = date('Y-m-d H:i:s', time());
        $start_time = strtotime("{$time} -1 day");
        $where = ['create_time' => ['elt', $start_time], 'remain_money' => ['egt', 1], 'status' => 1, 'is_receive' => 0];
        $count = $LuckmoneyM->where($where)->count();
        if ($count > 0) {
            $LuckMoney = $LuckmoneyM->field('luckmoney_id,remain_money,type,user_id')->where($where)->order('create_time asc')->limit('0,1000')->select();
            foreach ($LuckMoney as $v) {
                $data[] = [
                    'user_id' => $v['user_id'],
                    'money' => 'money+' . $v['remain_money'] * 100,
                ];

                $cashlog[] = [
                    'user_id' => $v['user_id'],
                    'money' => $v['remain_money'],
                    'type' => 'timeout_luckmoney',
                    'create_time' => time(),
                    'remark' => '退款',
                    'mtype' => 'money',
                    'extra' => '红包超时未领取',
                ];

                $ids[] = $v['luckmoney_id'];
            }
            M()->startTrans;
            $res1 = $this->db_batch_update('Users',$data, 'user_id','UPDATE bao_users ');
            $res2 = D('CashLog')->addAll($cashlog);
            if (!empty($res1) && !empty($res2)) {
                $LuckmoneyM->where(['luckmoney_id' => ['in', $ids]])->setField('is_receive', 1);
                M()->commit();
                return TRUE;
            }
        }
    }
    
    
    
/**
     * 批量更新数据
     * @param string $table_name
     * @param array $data
     * @param string $field
     * @return bool|false|int
     */
    function db_batch_update($table_name = '', $data = array(), $field = '',$sql='') {
        if (!$table_name || !$data || !$field) {
            return false;
        } else {
            $sql = $sql;//$sql= UPDATE users(表名)
        }
        $con = array();
        $con_sql = array();
        $fields = array();
        foreach ($data as $key => $value) {
            $x = 0;
            foreach ($value as $k => $v) {
                if ($k != $field && !$con[$x] && $x == 0) {
                    $con[$x] = " set {$k} = (CASE {$field} ";
                } elseif ($k != $field && !$con[$x] && $x > 0) {
                    $con[$x] = " {$k} = (CASE {$field} ";
                }
                if ($k != $field) {
                    $temp = $value[$field];
                    if(strpos($v,'+')){
                     $con_sql[$x].= " WHEN '{$temp}' THEN {$v} ";
                    }else{
                        $con_sql[$x].= " WHEN '{$temp}' THEN '{$v}' ";
                    }
                    
                    $x++;
                }
            }
            $temp = $value[$field];
            if (!in_array($temp, $fields)) {
                $fields[] = $temp;
            }
        }
        $num = count($con) - 1;
        foreach ($con as $key => $value) {
            foreach ($con_sql as $k => $v) {
                if ($k == $key && $key < $num) {
                    $sql.=$value . $v . ' end),';
                } elseif ($k == $key && $key == $num) {
                    $sql.=$value . $v . ' end)';
                }
            }
        }
        $str = implode(',', $fields);
        $sql.=" where {$field} in({$str})";
        $res = M($table_name)->execute($sql);
        return $res;
    }

}
